<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl视点和视线</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="800" height="800"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
attribute vec4 position;
attribute vec4 color;
uniform mat4 viewMatrix;
varying vec4 f_color;
void main(){
  gl_Position =viewMatrix* position;
  f_color=color;
}

`
  //片元着色器伪代码
  var fShder_source = `
  precision mediump  float;
  varying vec4 f_color;
void main(){
  gl_FragColor  = f_color; //设置颜色
}
`
  function main() {
    var canvas = document.getElementById('canvas');
    //  获取上下文对象
    var gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      return;
    }

    var n = initVertexBuffers(gl);
    var viewMat = gl.getUniformLocation(gl.program, "viewMatrix");

    //设置视角矩阵的相关信息（视点，视线，上方向）
    var viewMatrix = new Matrix4();
    viewMatrix.setLookAt(0, 0, -0.9, 0, 0, 0, 0, 1, 0);
    gl.uniformMatrix4fv(viewMat, false, viewMatrix.elements);

    // 指定一个覆盖canvas的颜色
    gl.clearColor(0, 0, 0, 1.0);
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, n);
  }

  function initVertexBuffers(gl) {
    var vertexDatas = new Float32Array([
      //顶点的坐标和颜色
      0.0, 0.5, -0.4, 0.4, 1.0, 0.4, // 绿色三角形，在最后面的三个点
      -0.5, -0.5, -0.4, 0.4, 1.0, 0.4,
      0.5, -0.5, -0.4, 1.0, 0.4, 0.4,

      0.5, 0.4, -0.2, 1.0, 0.4, 0.4, // 黄色三角形，在中间的三个点
      -0.5, 0.4, -0.2, 1.0, 1.0, 0.4,
      0.0, -0.6, -0.2, 1.0, 1.0, 0.4,

      0.0, 0.5, 0.0, 0.4, 0.4, 1.0,  // 蓝色三角形，在最前面的三个点
      -0.5, -0.5, 0.0, 0.4, 0.4, 1.0,
      0.5, -0.5, 0.0, 1.0, 0.4, 0.4
    ]);
    var n = 9;
    //创建缓冲区
    var vertexbuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexbuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexDatas, gl.STATIC_DRAW);
    var position = gl.getAttribLocation(gl.program, "position");
    var color = gl.getAttribLocation(gl.program, "color");
    var size = vertexDatas.BYTES_PER_ELEMENT;
    gl.vertexAttribPointer(position, 3, gl.FLOAT, false, size * 6, 0);
    gl.enableVertexAttribArray(position);
    gl.vertexAttribPointer(color, 3, gl.FLOAT, false, size * 6, size * 3);
    gl.enableVertexAttribArray(color);
    return n;

  }
</script>

</html>